from flask import Blueprint, jsonify, request
from services.chinese_words_service import ChineseWordsService
from utils.ocr import recognize_text
from utils.response import success_response, error_response
import base64
import urllib.parse



# 创建蓝图
words_bp = Blueprint('words', __name__)



# 初始化服务
words_service = ChineseWordsService()

# 获取词语列表（分页）- 同时支持带斜杠和不带斜杠的URL
@words_bp.route('/', methods=['GET'])
@words_bp.route('/<path:empty>', methods=['GET'])  # 处理URL末尾的斜杠或多余路径
@words_bp.route('', methods=['GET'])  # 确保不带斜杠也能访问
def get_words(empty=None):
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        search = request.args.get('search')
        
        # 验证参数
        if page < 1:
            page = 1
        if page_size < 1 or page_size > 100:
            page_size = 10
        
        # 调用服务层获取数据
        result = words_service.get_words_paginated(page, page_size, search)
        
        # 使用统一响应格式
        return success_response(
            message='获取词语列表成功',
            data=result['data'],
            pagination={
                'page': result['page'],
                'page_size': result['page_size'],
                'total': result['total'],
                'total_pages': result['total_pages']
            }
        )
    except Exception as e:
        return error_response(
            message='获取词语列表失败',
            error=str(e),
            status_code=500
        )

# 获取单个词语
@words_bp.route('/<int:word_id>', methods=['GET'])
def get_word(word_id):
    try:
        word = words_service.get_word_by_id(word_id)
        
        if word:
            return success_response(
                message='获取词语成功',
                data=word
            )
        else:
            return error_response(
                message='词语不存在',
                status_code=404
            )
    except Exception as e:
        return error_response(
            message='获取词语失败',
            error=str(e),
            status_code=500
        )

# 新增词语
@words_bp.route('/', methods=['POST'])
def add_word():
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['phrase', 'pinyin', 'meaning']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'status': 'error',
                    'message': f'缺少必要字段: {field}'
                }), 400
        
        # 调用服务层创建词语
        new_word = words_service.create_word(data)
        
        return jsonify({
            'status': 'success',
            'message': '词语创建成功',
            'data': new_word
        }), 201
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': '创建词语失败',
            'error': str(e)
        }), 500

# 更新词语
@words_bp.route('/<int:word_id>', methods=['PUT'])
def update_word(word_id):
    try:
        data = request.get_json()
        
        if not data:
            return error_response(
                message='更新数据不能为空',
                status_code=400
            )
        
        # 调用服务层更新词语
        updated_word = words_service.update_word(word_id, data)
        
        if updated_word:
            return success_response(
                message='词语更新成功',
                data=updated_word
            )
        else:
            return error_response(
                message='词语不存在',
                status_code=404
            )
    except Exception as e:
        return error_response(
            message='更新词语失败',
            error=str(e),
            status_code=500
        )

# 删除词语
@words_bp.route('/<int:word_id>', methods=['DELETE'])
def delete_word(word_id):
    try:
        # 调用服务层删除词语
        success = words_service.delete_word(word_id)
        
        if success:
            return success_response(
                message='词语删除成功'
            )
        else:
            return error_response(
                message='词语不存在',
                status_code=404
            )
    except Exception as e:
        return error_response(
            message='删除词语失败',
            error=str(e),
            status_code=500
        )

# 词语OCR识别
@words_bp.route('/ocr', methods=['POST'])
def word_ocr():
    try:
        # 检查是否有文件上传
        if 'file' not in request.files:
            return jsonify({
                'status': 'error',
                'message': '缺少必要文件: file'
            }), 400
        
        file = request.files['file']
        
        # 检查文件是否为空
        if file.filename == '':
            return jsonify({
                'status': 'error',
                'message': '未选择文件'
            }), 400
        
        # 检查文件类型
        allowed_extensions = {'jpg', 'jpeg', 'png', 'gif'}
        if '.' not in file.filename or file.filename.rsplit('.', 1)[1].lower() not in allowed_extensions:
            return jsonify({
                'status': 'error',
                'message': '不支持的文件类型，仅支持jpg、jpeg、png、gif'
            }), 400
        
        # 读取文件内容并转换为base64编码字符串
        file_content = base64.b64encode(file.read()).decode("utf8")
        # 调用OCR服务识别文字
        try:
            ocr_result = recognize_text(file_content)
            # 检查OCR结果中是否包含错误代码（使用字典键访问）
            if 'error_code' in ocr_result:
                return jsonify({
                    'status': 'error',
                    'message': 'OCR识别处理失败',
                    'error': ocr_result.get('error_msg', '未知错误')
                }), 500
            else:
                return jsonify({
                    'status': 'success',
                    'message': 'OCR识别成功',
                    'data': ocr_result
                }), 200
        except Exception as ocr_error:
            return jsonify({
                'status': 'error',
                'message': 'OCR识别处理失败',
                'error': str(ocr_error)
            }), 500
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': '识别失败',
            'error': str(e)
        }), 500


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content